/**
 *
 */
package com.ozq.common.controller.action;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ozq.common.controller.form.CommonForm;
import com.ozq.common.dao.entity.SpringJson;
import com.ozq.common.util.CacheUtils;
import com.ozq.common.util.UuidUtils;
import com.ozq.common.web.PermissionFilter;
import com.ozq.sys.dao.entity.SysArticle;
import com.ozq.sys.dao.entity.SysComment;
import com.ozq.sys.dao.entity.SysText;
import com.ozq.sys.dao.entity.SysUser;
import com.ozq.sys.service.inter.SysArticleService;
import com.ozq.sys.service.inter.SysCommentService;
import com.ozq.sys.service.inter.SysTextService;
import com.ozq.sys.service.inter.SysUserService;

import net.sf.ehcache.CacheManager;

/**
 * <首页控制>
 * <p>
 * <首页把控>
 * 
 * @author 欧增奇
 * @version [版本号, 2017年8月22日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Controller
public class IndexController
{
    static Logger logger = LoggerFactory.getLogger(IndexController.class);

    /**
     * 应用-文章表服务
     */
    @Autowired
    private SysArticleService sysArticleService;

    /**
     * 应用-系统-用户表服务
     */
    @Autowired
    private SysUserService sysUserService;

    /**
     * 应用-系统-文本表服务
     */
    @Autowired
    private SysTextService sysTextService;

    /**
     * 应用-评论表服务
     */
    @Autowired
    private SysCommentService sysCommentService;

    /**
     * 首页
     * 
     * @return
     */
    @RequestMapping("/")
    public String index(HttpServletRequest request)
    {
        // 统计文章
        SysArticle sysArticle = new SysArticle();
        sysArticle.setArticleStatus(1);
        request.setAttribute("countArticle", sysArticleService.countBy(sysArticle));

        // 统计用户
        SysUser sysUser = new SysUser();
        request.setAttribute("countUser", sysUserService.countBy(sysUser));

        // 统计评论
        SysComment sysComment = new SysComment();
        sysComment.setCommentStatus(1);
        sysComment.setCommentType(1);
        request.setAttribute("countComment", sysCommentService.countBy(sysComment));

        setToKen(request);
        return "index";
    }

    /**
     * 跳转页面
     * 
     * @return
     */
    @RequestMapping("{catalog}/{file}.html")
    public String catalogFile(HttpServletRequest request, @PathVariable("catalog") String catalog, @PathVariable("file") String file)
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("debug catalog:{}", catalog);
            logger.debug("debug file:{}", file);
        }

        setToKen(request);
        return catalog + "/" + file;
    }

    /**
     * 查看文章详情-修改
     * 
     * @return
     */
    @RequestMapping("share/article/{articleCode}.html")
    public String shareArticleId(HttpServletRequest request, @PathVariable("articleCode") String articleCode)
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("debug articleCode:{}", articleCode);
        }

        SysArticle sysArticle = new SysArticle();
        sysArticle.setArticleCode(articleCode);
        sysArticle.setArticleStatus(1);
        sysArticle = sysArticleService.find(sysArticle);

        if (sysArticle == null)
        {
            return "common/error";
        }

        // 查询具体内容
        SysText sysText = new SysText();
        sysText.setTextCode(sysArticle.getTextCode());
        sysText = sysTextService.find(sysText);

        request.setAttribute("sysText", sysText);
        request.setAttribute("sysArticle", sysArticle);

        setToKen(request);
        return "share/article";
    }

    /**
     * 查看文章详情
     * 
     * @return
     */
    @RequestMapping("detail/{articleCode}.html")
    public String detailArticleId(HttpServletRequest request, @PathVariable("articleCode") String articleCode)
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("debug articleCode:{}", articleCode);
        }

        SysArticle sysArticle = new SysArticle();
        sysArticle.setArticleCode(articleCode);
        sysArticle.setArticleStatus(1);
        sysArticle = sysArticleService.find(sysArticle);

        if (sysArticle == null)
        {
            return "common/error";
        }

        // 计算访问量
        // 数量
        BigDecimal count = (BigDecimal) CacheUtils.get("count_" + sysArticle.getArticleCode(), CacheUtils.COUNT_ARTICLE);
        // 时间
        Date date = (Date) CacheUtils.get("count_time_" + sysArticle.getArticleCode(), CacheUtils.COUNT_ARTICLE);

        // 为空记录
        if (count == null || date == null)
        {
            count = sysArticle.getArticleClick();
            CacheUtils.put("count_" + sysArticle.getArticleCode(), count, CacheUtils.COUNT_ARTICLE);
            date = new Date();
            CacheUtils.put("count_time_" + sysArticle.getArticleCode(), date, CacheUtils.COUNT_ARTICLE);
        }
        count = count.add(BigDecimal.ONE);
        CacheUtils.put("count_" + sysArticle.getArticleCode(), count, CacheUtils.COUNT_ARTICLE);

        // 判断是否超过6小时更新一次数据
        Long time = System.currentTimeMillis();
        int exceedTime = (int) ((time - date.getTime()) / (1000 * 60 * 60 * 6));
        if (exceedTime > 1)
        {
            sysArticle.setArticleClick(count);
            sysArticleService.update(sysArticle);
            CacheUtils.remove("count_" + sysArticle.getArticleCode(), CacheUtils.COUNT_ARTICLE);
            CacheUtils.remove("count_time_" + sysArticle.getArticleCode(), CacheUtils.COUNT_ARTICLE);
        }

        // 查询用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUserCode(sysArticle.getUserCode());
        sysUser = sysUserService.find(sysUser);

        // 查询具体内容
        SysText sysText = new SysText();
        sysText.setTextCode(sysArticle.getTextCode());
        sysText = sysTextService.find(sysText);

        // 统计评论
        SysComment sysComment = new SysComment();
        sysComment.setArticleCode(sysArticle.getArticleCode());
        sysComment.setCommentType(1);

        request.setAttribute("sysArticle", sysArticle);
        request.setAttribute("sysUser", sysUser);
        request.setAttribute("sysText", sysText);
        request.setAttribute("countSysComment", sysCommentService.countLike(sysComment));

        setToKen(request);
        return "share/detail";
    }

    /**
     * 公共-清理缓存-执行
     * 
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "update/cache/do", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public SpringJson updateCacheDo(HttpServletRequest request, CommonForm commonForm)
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("debug commonForm:{}", commonForm);
        }

        try
        {
            List<String> methods = commonForm.getCaches();
            for (String methodName : methods)
            {
                if (StringUtils.isNotEmpty(methodName))
                {
                    CacheManager cacheManager = CacheManager.getInstance();
                    cacheManager.getEhcache(methodName).removeAll();
                }
            }
            return new SpringJson(true);
        } catch (Exception e)
        {
            return new SpringJson(false);
        }
    }

    /**
     * 设置页面token
     * 
     * @param request
     */
    private void setToKen(HttpServletRequest request)
    {
        String key = CacheUtils.TOKEN + HashCodeBuilder.reflectionHashCode(PermissionFilter.getIpAddr(request));
        // 可以先查询，如果存在，直接保存，不存在才创建
        String token = Base64Utils.encodeToString(UuidUtils.random(21).getBytes());
        CacheUtils.put(key, token, CacheUtils.TOKEN);
        request.setAttribute("token", token);
    }
}
